import { userService } from './leancloud-helper';
import _ from 'lodash';

export const fmtDate = (arr) => {
  const res = {};
  for (const iterator of arr) {
    const temp = {
      id: iterator.id,
      ...iterator.attributes,
      role: {
        id: iterator.attributes.role.id,
        ...iterator.attributes.role.attributes
      }
    }
    const groupName = temp.role.name;

    if (Object.hasOwn(res, groupName)) {
      res[groupName].push(temp)
    } else {
      res[groupName] = [temp]
    }
  }
  return res;
}


// 计算最小公倍数
function calculateLCM(arr) {
  let lcm = arr[0];
  for (let i = 1; i < arr.length; i++) {
    lcm = (lcm * arr[i]) / calculateGCD(lcm, arr[i]);
  }
  return lcm;
}

// 计算最大公约数
function calculateGCD(a, b) {
  if (b === 0) {
    return a;
  }
  return calculateGCD(b, a % b);
}
// 计算主函数
const scheduleRotation = (peopleArray) => {
  const rotationArray = [];
  const categories = peopleArray.length;
  let maxCycle = Math.max(...peopleArray.map(category => category.length));
  const lcm = calculateLCM(peopleArray.map(category => category.length));

  // 补充人员
  for (let i = 0; i < categories; i++) {
    const categoryPeople = peopleArray[i];
    if (categoryPeople.length < lcm) {
      const additionalPeople = categoryPeople.slice();
      while (additionalPeople.length < lcm) {
        additionalPeople.push(...categoryPeople);
      }
      peopleArray[i] = additionalPeople;
    }
  }

  // 安排轮班
  for (let i = 0; i < lcm; i++) {
    const dayPeople = [];
    for (let j = 0; j < categories; j++) {
      const categoryPeople = peopleArray[j];
      dayPeople.push(categoryPeople[i % categoryPeople.length]);
    }
    rotationArray.push(dayPeople);
  }

  return rotationArray;
}


const groupLen = (array, subGroupLength)=> {
  let index = 0;
  let newArray = [];
  while(index < array.length) {
      newArray.push(array.slice(index, index += subGroupLength));
  }
  return newArray;
}





export const paiBan = async () => {
  const res1 = await userService.query();
  const res2 = fmtDate(res1);
  const res3 = Object.values(res2);
  const res4 = scheduleRotation(_.cloneDeep(res3));
  const res5 = groupLen(res4, 6);

  // 将每周的（组）人员顺序打乱(为避免日期固定)
  res5.forEach((group,index)=>{
    res5[index] = _.shuffle(group);
  })

  return res5;
}